package info.emm.weiyipro.demo;


import android.content.Intent;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.util.ArrayMap;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;


import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONObject;
import org.webrtc.EglBase;
import org.webrtc.RendererCommon;
import org.webrtc.SurfaceViewRenderer;

import java.util.ArrayList;
import java.util.HashMap;

import info.emm.weiyipro.demo.sdk.WySdk;
import info.emm.weiyipro.demo.sdk.system.AudioPlayManager;
import wy.base.ActionCallback;
import wy.base.LocalStream;
import wy.base.WyError;
import wy.conference.ConferenceClient;
import wy.conference.ConferenceInfo;
import wy.conference.Participant;
import wy.conference.Publication;
import wy.conference.RemoteStream;


/**
 * 不带界面sdk
 * 简单版
 */

public class ActivityMeeting extends AppCompatActivity implements ConferenceClient.ConferenceClientObserver, ActionCallback<RemoteStream> {

    private static final String TAG = "WY";
    private SurfaceViewRenderer remote_surface;
    private SurfaceViewRenderer local_surface;
    private String mUserId;
    private String serial;//roomId
    private ImageView video;
    private ImageView quit;
    private boolean isLeft;
    private AudioManager audioManager;
    private ConferenceInfo conferenceInfo;
    private ArrayList<String> remoteStreamIdList = new ArrayList<>();
    private ArrayMap<String, RemoteStream> remoteStreamMap = new ArrayMap<>();
    private Publication publication;
    private TextView send_message;

    public static void startEnter(AppCompatActivity activity, String userId, String serial) {
        Bundle bundle = new Bundle();
        bundle.putString("userId", userId);
        bundle.putString("serial", serial);
        Intent intent = new Intent(activity, ActivityMeeting.class);
        intent.putExtras(bundle);
        activity.startActivity(intent);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK://返回键
                WySdk.instance().exitMeeting();
                finish();
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meeting);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        Bundle bundleExtra = getIntent().getExtras();


        if (bundleExtra != null) {
            mUserId = bundleExtra.getString("userId");
            serial = bundleExtra.getString("serial");
        }
        initView();
        join();
        initVolume();
    }

    private void initVolume() {
        AudioPlayManager.getManager().changeToSpeakerMode();
    }
    @Override
    protected void onDestroy() {

        //释放surface
        if (local_surface != null)
            local_surface.release();
        if (remote_surface != null)
            remote_surface.release();
        //停止拉流
        for (String streamId : remoteStreamIdList) {
            RemoteStream remoteStream = remoteStreamMap.get(streamId);
            if (remoteStream != null)
                WySdk.instance().stopSubscribe(remoteStream);
        }
        AudioPlayManager.getManager().changeNormal();
        WySdk.instance().exitMeeting();
        super.onDestroy();
    }

    private void join() {
        WySdk.instance().addObserver(this);
        WySdk.instance().joinRoom("https://test.weiyipro.com:3004", mUserId, serial, new ActionCallback<ConferenceInfo>() {
            @Override
            public void onSuccess(ConferenceInfo result) {
                conferenceInfo = result;
                LocalStream localStream = WySdk.instance().cteatLocalStream();

                localStream.attach(local_surface);
                WySdk.instance().publishStream(new ActionCallback<Publication>() {
                    @Override
                    public void onSuccess(Publication publication) {
                        ActivityMeeting.this.publication = publication;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                video.setSelected(true);
                            }
                        });

                    }

                    @Override
                    public void onFailure(WyError wyError) {

                    }
                });


                /**
                 * 进入会议之前已经存在的流
                 */
                for (RemoteStream remoteStream : conferenceInfo.getRemoteStreams()) {
                    addStreamObserver(remoteStream);
                }
                /**
                 * 进入会议之前已经存在的参与者
                 */
                for (Participant participant : conferenceInfo.getParticipants()) {

                }
            }

            @Override
            public void onFailure(WyError wyError) {

            }

        });
    }

    private void addStreamObserver(RemoteStream remoteStream) {
        WySdk.instance().getParameterByRemoteStream(remoteStream);
        remoteStreamIdList.add(remoteStream.id());

        remoteStreamMap.put(remoteStream.id(), remoteStream);
        remoteStream.addObserver(new wy.base.RemoteStream.StreamObserver() {
            @Override
            public void onEnded() {
                remoteStreamIdList.remove(remoteStream.id());

                remoteStreamMap.remove(remoteStream.id());

            }

            @Override
            public void onUpdated() {

            }
        });
    }

    private void initView() {
        remote_surface = findViewById(R.id.remote_surface);
        local_surface = findViewById(R.id.local_surface);
        send_message = findViewById(R.id.send_message);
        EglBase.Context sharedContext = WySdk.getRootEglBase().getEglBaseContext();

        local_surface.init(sharedContext, null);
        local_surface.setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FIT);
        local_surface.setEnableHardwareScaler(true);
        local_surface.setZOrderMediaOverlay(true);
        local_surface.setMirror(true);

        remote_surface.init(sharedContext, null);
        remote_surface.setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FIT);
        remote_surface.setEnableHardwareScaler(true);

        video = findViewById(R.id.video);
        quit = findViewById(R.id.quit);


        quit.setOnClickListener(v -> {
            isLeft = true;
            WySdk.instance().exitMeeting();
            finish();
        });

        video.setOnClickListener(v -> {
            videoClick();
        });
        send_message.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                WySdk.instance().send("textName", "others", new Object(), new ActionCallback<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Log.d(TAG, "onSuccess: " );
                    }

                    @Override
                    public void onFailure(WyError wyError) {
                        Log.e(TAG, "onFailure: "+wyError.errorMessage );
                    }
                });
            }
        });

    }

    private void videoClick() {
        if (!video.isSelected()) {
            video.setEnabled(false);
            WySdk.instance().publishStream(new ActionCallback<Publication>() {
                @Override
                public void onSuccess(Publication publication) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            video.setEnabled(true);
                            video.setSelected(true);
                        }
                    });
                }

                @Override
                public void onFailure(WyError wyError) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            video.setEnabled(true);
                        }
                    });
                }
            });
        } else {
            video.setSelected(false);
            WySdk.instance().stopPublishStream();
        }
    }

    @Override
    protected void onResume() {
        WySdk.instance().restStartCapturer();
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onServerDisconnected() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        });
    }

    /**
     * 加入会议之后加入进来的流
     * 加入会议之前的流 {@link ConferenceInfo#getRemoteStreams()}}
     * remoteStream.origin()与participant.id()相同
     * 流的其他自定义属性参考 {@link  WySdk#USERID}
     *
     * @param remoteStream
     */
    @Override
    public void onStreamAdded(RemoteStream remoteStream) {


        addStreamObserver(remoteStream);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                HashMap<String, String> attributes = remoteStream.getAttributes();
                if (attributes != null) {
                    String userId = attributes.get(WySdk.USERID);
                    Log.e(TAG, "onStreamAdded:userId:  " + userId);
                }
                /**
                 * 拉取加入会议之后加入进来的流，此处并没有任何业务逻辑判断，仅作为参考拉取流媒体用
                 */
                WySdk.instance().subscribeStream(remoteStream, ActivityMeeting.this);
            }
        });
    }

    /**
     * 某个参会者进入会议
     * 加入会议之前的参与者 {@link ConferenceInfo#getParticipants()}
     * participant.userId 为传入的userId
     * participant.id 与 remoteStream.origin() 相同
     *
     * @param participant
     */
    @Override
    public void onParticipantJoined(Participant participant) {
        Log.e(TAG, "onParticipantJoined: " + participant.userId);
    }

    /**
     * 接收的信令消息
     *
     * @param json   消息json
     * @param fromID 发送消息的id
     * @param toID   发送给toId
     */
    @Override
    public void onMessageReceived(String json, String fromID, String toID) {
        Log.d(TAG, "onMessageReceived: " + json);
    }


    /**
     * 拉取流媒体成功回调
     *
     * @param remoteStream
     */
    @Override
    public void onSuccess(final RemoteStream remoteStream) {
        String origin = remoteStream.origin();

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                HashMap<String, String> attributes = remoteStream.getAttributes();
                if (attributes != null) {
                    String userId = attributes.get(WySdk.USERID);
                    Log.e(TAG, "subSuccess:userId:  " + userId);
                }
                remoteStream.attach(remote_surface);
            }
        });
    }

    /**
     * 拉取流媒体失败回调
     *
     * @param wyError
     */
    @Override
    public void onFailure(WyError wyError) {
        Log.e(TAG, "subFailure:" + wyError.errorMessage);

    }
}
